package com.duan.laugh.activiti.controller;

import cn.hutool.core.io.IoUtil;
import com.duan.laugh.activiti.service.ProcessService;
import com.duan.laugh.common.core.util.R;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.InputStream;
import java.util.Map;

/**
 * 流程 controller
 *
 * @author duanjw
 */
@RestController
@AllArgsConstructor
@RequestMapping("/process")
public class ProcessController {
    private final ProcessService processService;

    /**
     * 分页查询流程
     *
     * @param params
     * @return
     */
    @GetMapping
    public R selectPage(@RequestParam Map<String, Object> params) {
        return R.ok(processService.selectPage(params));
    }

    @GetMapping(value = "/resource/{proInsId}/{procDefId}/{resType}")
    public ResponseEntity resourceRead(@PathVariable String procDefId, @PathVariable String proInsId, @PathVariable String resType) {

        HttpHeaders headers = new HttpHeaders();

//        if (ResourceTypeEnum.XML.getType().equals(resType)) {
//            headers.setContentType(MediaType.APPLICATION_XML);
//        } else {
//            headers.setContentType(MediaType.IMAGE_PNG);
//        }

        InputStream resourceAsStream = processService.readResource(procDefId, proInsId, resType);
        return new ResponseEntity(IoUtil.readBytes(resourceAsStream), HttpStatus.CREATED);
    }

    @PutMapping("/status/{procDefId}/{status}")
    public R updateState(@PathVariable String procDefId, @PathVariable String status) {
        return R.ok(processService.updateStatus(status, procDefId));
    }

    @DeleteMapping("/{deploymentId}")
    public R deleteProcIns(@PathVariable String deploymentId) {
        return R.ok(processService.removeProcIns(deploymentId));
    }

    /**
     * 启动流程实例
     *
     * @param processId
     * @return
     */
    @PutMapping("/status/start/{processId}")
    public R startProcess(@PathVariable String processId) {
        return R.ok(processService.startProcess(processId));
    }

    /**
     * 分页查询流程下的所有任务
     *
     * @param processId 流程id
     * @param params    分页参数
     * @return
     */
    @GetMapping("/{processId}/task")
    public R selectTaskPageByProcessId(@PathVariable String processId, @RequestParam Map<String, Object> params) {
        return R.ok(processService.selectTaskPageByProcessId(processId, params));
    }
}
